<template>
  <div class="app-container">
    <div class="form-container">
      <el-form ref="queryForm" :model="filters" :inline="true" label-width="80px">
        <el-form-item label="字典名称" prop="dictType">
          <el-select v-model="filters.dictType" size="small">
            <el-option
              v-for="item in typeOptions"
              :key="item.dictId"
              :label="item.dictName"
              :value="item.dictType"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="字典标签" prop="dictLabel">
          <el-input
            v-model="filters.dictLabel"
            placeholder="请输入字典标签"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="数据状态" prop="status">
          <el-select
            v-model="filters.status"
            placeholder="数据状态"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <!-- 高级设置一栏 start -->
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="dateRange"
            size="small"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="true"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="btns-group">
      <systemBtns :single="single" has-permi="dict" />
      <el-button v-show="status === '1'" size="middle" :disabled="single" icon="el-icon-star-on" @click="handleStatusChange">
        启用
      </el-button>
      <el-button v-show="status === '0'" size="middle" :disabled="single" icon="el-icon-star-off" @click="handleStatusChange">
        停用
      </el-button>
      <span class="personal-type">
        <el-button icon="el-icon-arrow-left" size="middle" @click="handleReturn()">返回</el-button>
      </span>
    </div>

    <el-table
      ref="multipleTable"
      v-loading="loading"
      stripe
      :class="highLevelSet===true ? (needTagsView===true ? 'el-body-page-roll-tag-height' : 'el-body-page-roll-height') :
        (needTagsView===true ? 'el-body-page-roll-tag' : 'el-body-page-roll')"
      class="table-list"
      :row-style="rowClass"
      :data="dataList"
      @selection-change="handleSelectionChange"
      @row-click="rowChecked"
    >
      <el-table-column type="selection" width="38" align="center" />
      <el-table-column label="字典编码" align="center" prop="dictCode" />
      <el-table-column label="字典标签" align="center" prop="dictLabel" />
      <el-table-column label="字典键值" align="center" prop="dictValue" />
      <el-table-column label="字典排序" align="center" prop="dictSort" />
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span v-if="scope.row.createTime">{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="filters.pageNum"
      :limit.sync="filters.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <dataDialog ref="dataDialog" :status-options="statusOptions" />
  </div>
</template>

<script>
import dataDialog from './components/dataDialog'
import { listData, delData, updateData } from '@/api/system-tool/dict/data'
import { listType, getType } from '@/api/system-tool/dict/type'
import { mapState } from 'vuex'
// 按钮组件
import systemBtns from '@/components/Common/Btns/systemBtns'
export default {
  name: 'Data',
  components: {
    systemBtns,
    dataDialog
  },
  data() {
    return {
      // 高级设置显示隐藏
      highLevelSet: false,
      // 高级设置参数
      highLevelSettingData: [
        {
          label: '创建时间',
          isDatePicker: 1,
          size: 'small',
          type: 'daterange',
          separator: '-',
          start: '开始日期',
          end: '结束日期',
          isClearable: false,
          prop: 'createTime',
          model: []
        }
      ],
      // 时间范围数组
      dateRange: [],
      status: '0',
      // 高亮数组
      selectRow: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选择的行对象
      multipleSelection: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字典表格数据
      dataList: [],
      // 默认字典类型
      defaultDictType: '',
      // 状态数据字典
      statusOptions: [],
      // 类型数据字典
      typeOptions: [],
      // 查询参数
      filters: {
        pageNum: 1,
        pageSize: this.fristPageSize,
        dictType: '',
        dictLabel: '',
        status: '0'
      }
    }
  },
  computed: {
    ...mapState({
      needTagsView: state => state.settings.tagsView
    }),
    // 高级搜索显示隐藏
    handleTagShow() {
      return this.highLevelSet
    }
  },
  watch: {
    // 高亮样式
    multipleSelection(data) {
      this.selectRow = []
      if (data.length > 0) {
        data.forEach((item, index) => {
          this.selectRow.push(this.dataList.indexOf(item))
        })
      }
    }
  },
  created() {
    const dictId = this.$route.params && this.$route.params.dictId
    this.getType(dictId)
    this.getTypeList()
    this.getDicts('sys_normal_disable').then(res => {
      this.statusOptions = res.data.rows
    })
  },
  methods: {
    // 获取高级设置中子组件传递的数据
    getValueFromChild(data) {
      this.highLevelQueryParams = data
    },
    /** 查询字典类型详细 */
    getType(dictId) {
      getType(dictId).then(res => {
        this.filters.dictType = res.data.dictType
        this.defaultDictType = res.data.dictType
        this.getList()
      })
    },
    /** 查询字典类型列表 */
    getTypeList() {
      listType().then(res => {
        this.typeOptions = res.data.rows
      })
    },
    /** 查询字典数据列表 */
    getList() {
      this.loading = true
      listData(this.changeDateRange(this.filters, this.dateRange)).then(res => {
        this.dataList = res.data.rows
        this.total = res.data.total
        this.loading = false
        // this.addTaleData()
      })
    },
    // list表格填充空白行
    addTaleData() {
      if (this.dataList.length < this.fristPageSize) {
        const arr = {}
        this.dataList.push(arr)
        this.addTaleData()
      }
    },
    // 数据状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 单击每行时每行的复选框选中
    rowChecked(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    // 返回
    handleReturn() {
      this.$router.go(-1)
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // 将高级设置所要查询的字段放到查询参数的对象中，key值自定义，与后台配合
      // 高级设置组件显示则查询，不显示则清空高级设置中添加的查询字段
      if (this.highLevelSet === true) {
        if (this.highLevelQueryParams[0].model !== '') {
          this.dateRange = this.highLevelQueryParams[0].model
        }
      } else {
        this.dateRange = []
      }
      this.filters.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.dateRange = []
      this.highLevelSettingData[0].model = []
      this.filters.dictType = this.defaultDictType
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      if (this.multipleSelection.length === 1) {
        this.status = this.multipleSelection[0].status
      }
      this.ids = selection.map(item => item.dictCode)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.dataDialog.handleAdd('新增字典数据', this.filters.dictType)
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.$refs.dataDialog.handleAdd('修改字典数据', this.filters.dictType, this.ids)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let dictCodes = ''
      const child = this.multipleSelection
      for (let i = 0; i < child.length; i++) {
        dictCodes += child[i].dictCode + ','
      }
      // 去掉最后一个逗号
      if (dictCodes.length > 0) {
        dictCodes = dictCodes.substr(0, dictCodes.length - 1)
      }
      this.$confirm(
        '是否确认删除该数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delData(dictCodes)
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(function() {})
    },
    // 用户状态修改
    handleStatusChange() {
      const { dictType } = this.filters
      const row = this.multipleSelection[0]
      const text = row.status === '0' ? '停用' : '启用'
      this.$confirm('确认要' + text + '' + '所选项吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          let status = ''
          if (row.status === '0') {
            status = '1'
          } else {
            status = '0'
          }
          const { dictCode, dictLabel, dictValue, dictSort, remark } = row
          updateData({ dictType, status, dictCode, dictLabel, dictValue, dictSort, remark }).then(resp => {
            if (resp) {
              this.getList()
              this.msgSuccess('操作成功！')
            } else {
              this.msgError(resp.message)
            }
          })
        })
        .catch(() => {
          this.msgInfo('已取消')
        })
    },
    // 高亮样式
    rowClass({ row, rowIndex }) {
      if (this.selectRow.includes(rowIndex)) {
        return { 'background-color': 'rgba(185,221,249,.75)' }
      }
    }
  }
}
</script>
